<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="filter-container" shadow="never">
      <div class="filter-item">
        <el-select v-model="queryParams.categoryId" placeholder="请选择分类" style="width: 200px" @change="handleQuery">
          <el-option v-for="item in categoryOptions" :key="item.categoryId" :label="item.categoryName"
            :value="item.categoryId" />
        </el-select>
        <el-button style="margin-left: 10px;" type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
        <el-button type="primary" @click="handleAdd" v-hasPermi="['system:product:add']">新增</el-button>
      </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-container">
      <el-table v-loading="loading" :data="tableData" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="mainImage" label="商品图片">
          <template #default="{ row }">
            <el-image style="width: 80px; height: 80px" :src="row.mainImage" :preview-src-list="[row.mainImage]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="商品名称" />
        <el-table-column prop="description" label="商品描述" show-overflow-tooltip />
        <el-table-column prop="symptoms" label="治疗症状"></el-table-column>
        <el-table-column prop="price" label="售价" width="100">
          <template #default="{ row }">
            ¥{{ row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="originalPrice" label="原价" width="100">
          <template #default="{ row }">
            ¥{{ row.originalPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="memberPrice" label="会员价" width="100">
          <template #default="{ row }">
            ¥{{ row.memberPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="80" />
        <el-table-column prop="manufacturer" label="生产厂家" show-overflow-tooltip />
        <el-table-column prop="specification" label="规格" show-overflow-tooltip />
        <el-table-column prop="isOtc" label="是否OTC">
          <template #default="{ row }">
            <el-tag :type="row.isOtc === 1 ? 'success' : 'info'">
              {{ row.isOtc === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isPrescription" label="是否处方药">
          <template #default="{ row }">
            <el-tag :type="row.isPrescription === 1 ? 'warning' : 'success'">
              {{ row.isPrescription === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.status === 0 ? 'success' : 'info'">
              {{ row.status === 0 ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="{ row }">
            <el-button size="mini" type="text" @click="handleUpdate(row)"
              v-hasPermi="['system:product:edit']">编辑</el-button>
            <el-button size="mini" type="text" @click="handleDelete(row)"
              v-hasPermi="['system:product:delete']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="60%" :before-close="handleClose">
      <el-form :model="form" label-width="120px" ref="formRef" :rules="rules">
        <el-form-item label="商品名称" required>
          <el-input v-model="form.name" />
        </el-form-item>

        <!-- 商品图片上传 -->
        <el-form-item label="商品主图" required>
          <div class="upload-box">
            <el-upload class="upload-demo" :action="action" :headers="{ Authorization: 'Bearer ' + getTk() }"
              :show-file-list="true" :file-list="mainImageList" list-type="picture-card" :limit="1" :on-success="handleMainImageSuccess"
              :on-remove="handleMainImageRemove" accept="image/jpeg,image/png,image/jpg">
              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
          </div>
          <div class="upload-tip">支持jpg、png格式，建议尺寸800x800，单张不超过10M</div>
        </el-form-item>

        <!-- 商品图片集上传 -->
        <el-form-item label="商品图片集">
          <div class="upload-box">
            <el-upload class="upload-demo" :action="action" :headers="{ Authorization: 'Bearer ' + getTk() }" :limit="5"
              :show-file-list="true" :file-list="imageList" list-type="picture-card" :on-success="handleImageSuccess" :on-remove="handleImageRemove"
              multiple accept="image/jpeg,image/png,image/jpg">
              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
          </div>
          <div class="upload-tip">最多上传5张图片</div>
        </el-form-item>

        <el-form-item label="商品分类" required>
          <el-select v-model="form.categoryId">
            <el-option v-for="item in categoryList" :key="item.categoryId" :label="item.categoryName"
              :value="item.categoryId" />
          </el-select>
        </el-form-item>

        <el-form-item label="商品描述" required>
          <el-input v-model="form.description" type="textarea" :rows="4" />
        </el-form-item>

        <el-form-item label="生产厂家">
          <el-input v-model="form.manufacturer" />
        </el-form-item>

        <el-form-item label="批准文号">
          <el-input v-model="form.approvalNumber" />
        </el-form-item>

        <el-form-item label="规格">
          <el-input v-model="form.specification" />
        </el-form-item>

        <el-form-item label="用法用量">
          <el-input v-model="form.usage" type="textarea" :rows="3" />
        </el-form-item>

        <el-form-item label="注意事项">
          <el-input v-model="form.precautions" type="textarea" :rows="3" />
        </el-form-item>

        <el-form-item label="库存" required>
          <el-input-number v-model="form.stock" :min="0" />
        </el-form-item>

        <el-form-item label="是否处方药">
          <el-switch v-model="form.isPrescription" :active-value="1" :inactive-value="0" />
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="form.status">
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>

        <el-form-item label="排序">
          <el-input-number v-model="form.sort" :min="0" />
        </el-form-item>

        <el-form-item label="价格" required>
          <el-input-number v-model="form.price" :min="0" :precision="2" :step="0.1" />
        </el-form-item>

        <el-form-item label="原价" required>
          <el-input-number v-model="form.originalPrice" :min="0" :precision="2" :step="0.1" />
        </el-form-item>

        <el-form-item label="会员价" required>
          <el-input-number v-model="form.memberPrice" :min="0" :precision="2" :step="0.1" />
        </el-form-item>

        <el-form-item label="治疗症状" prop="symptoms">
          <el-select v-model="form.symptoms" multiple filterable allow-create default-first-option
            placeholder="请选择或输入治疗症状" class="w-full">
            <el-option v-for="item in symptomOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getToken } from '@/utils/auth'
import {
  getProductList,
  getProductDetail,
  addProduct,
  updateProduct,
  deleteProduct,
  listCategory
} from '@/api/product'

interface Category {
  categoryId: number
  categoryName: string
}

interface ProductForm {
  id?: number
  name: string
  productName?: string
  description: string
  stock: number
  isPrescription: number
  categoryId?: number
  status: number
  sort: number
  mainImage: string
  images: string[]
  price: number
  originalPrice: number
  memberPrice: number
  manufacturer: string
  approvalNumber: string
  specification: string
  usage: string
  precautions: string
  symptoms: string[]
}

const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref<FormInstance>()
const categoryList = ref<Category[]>([])
const mainImageList = ref<any[]>([])
const imageList = ref<any[]>([])
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  categoryId: undefined
})
const categoryOptions = ref<Category[]>([])
// const action = ref('http://localhost:8498/common/upload')
const action = ref('http://175.178.54.148:8498/common/upload')

// 症状选项
const symptomOptions = ref([
  "头痛", "眩晕", "失眠", "健忘", "耳鸣", "耳聋", "视力模糊", "咽喉肿痛",
  "咳嗽", "气喘", "胸闷", "心悸", "胃痛", "胃胀", "腹泻", "便秘",
  "腰酸背痛", "关节疼痛", "痛经", "月经不调", "崩漏", "带下病", "面部色斑",
  "痤疮", "湿疹", "荨麻疹", "皮炎", "风湿痹痛", "中风后遗症", "糖尿病",
  "高血压", "高血脂", "肥胖症", "贫血", "营养不良", "慢性疲劳综合征"
])

// 表单参数
const form = ref<ProductForm>({
  id: undefined,
  name: '',
  productName: '',
  description: '',
  stock: 0,
  isPrescription: 0,
  categoryId: undefined,
  status: 1,
  sort: 0,
  mainImage: '',
  images: [],
  price: 0,
  originalPrice: 0,
  memberPrice: 0,
  manufacturer: '',
  approvalNumber: '',
  specification: '',
  usage: '',
  precautions: '',
  symptoms: []
})

// 表单校验规则
const rules = reactive<FormRules>({
  name: [
    { required: true, message: "商品名称不能为空", trigger: "blur" }
  ],
  mainImage: [
    { required: true, message: "商品主图不能为空", trigger: "blur" }
  ],
  categoryId: [
    { required: true, message: "商品分类不能为空", trigger: "blur" }
  ],
  description: [
    { required: true, message: "商品描述不能为空", trigger: "blur" }
  ],
  stock: [
    { required: true, message: "库存不能为空", trigger: "blur" }
  ],
  price: [
    { required: true, message: "商品价格不能为空", trigger: "blur" }
  ],
  symptoms: [
    { required: true, message: "请选择治疗症状", trigger: "change" }
  ]
})

// 获取分类列表
const loadCategories = async () => {
  try {
    const res = await listCategory()
    if (res.code == 200) {
      categoryList.value = res.data
      categoryOptions.value = res.data
      if (res.data.length > 0) {
        queryParams.value.categoryId = res.data[0].categoryId
        getList()
      }
    } else {
      ElMessage.error(res.msg || '获取分类列表失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('获取分类列表失败')
  }
}

// 图片上传成功处理
const handleMainImageSuccess = (res: any) => {
  form.value.mainImage = res.url
}

const handleImageSuccess = (res: any) => {
  console.log(res, 'rrrr')
  form.value.images.push(res.url)
}

// 分类变更
const handleCategoryChange = () => {
  queryParams.value.pageNum = 1
  getList()
}

// 查询商品列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getProductList(queryParams.value)

    console.log(res, 'rrrr')
    if (res.code == 200) {
      tableData.value = res.data.list
      total.value = res.data.total
    }
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 查询按钮操作
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
}

const getTk = () => {
  return getToken()
}

// 重置按钮操作
const resetQuery = () => {
  if (categoryOptions.value.length > 0) {
    queryParams.value.categoryId = categoryOptions.value[0].categoryId
  }
  queryParams.value.pageNum = 1
  handleQuery()
}

// 新增商品
const handleAdd = () => {
  reset()
  dialogTitle.value = '新增商品'
  dialogVisible.value = true
}

// 编辑商品
const handleUpdate = async (row: any) => {
  reset()
  try {
    const res = await getProductDetail(row.id)
    if (res.code == 200) {
      Object.assign(form.value, res.data)
      // 处理symptoms字符串为数组
      if (form.value.symptoms) {
        form.value.symptoms = form.value.symptoms.split(',')
      } else {
        form.value.symptoms = []
      }
      // 设置图片列表
      if (form.value.mainImage) {
        mainImageList.value = [{
          name: '主图',
          url: form.value.mainImage
        }]
      }
      if (form.value.images && form.value.images.length > 0) {
        imageList.value = form.value.images.map((url: string) => ({
          name: '商品图片',
          url
        }))
      }
      if (form.value.productName) {
        form.value.name = form.value.productName
      }
      dialogTitle.value = '编辑商品'
      dialogVisible.value = true
    } else {
      ElMessage.error(res.msg || '获取商品详情失败')
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败')
  }
}

// 删除商品
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确认删除该商品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteProduct(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error(error)
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 处理symptoms数组为字符串
        const submitData = { ...form.value }
        if (Array.isArray(submitData.symptoms)) {
          submitData.symptoms = submitData.symptoms.join(',')
        }
        
        if (form.value.id) {
          await updateProduct(submitData)
          ElMessage.success('更新成功')
        } else {
          await addProduct(submitData)
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 表单重置
const reset = () => {
  form.value = {
    id: undefined,
    name: '',
    productName: '',
    description: '',
    stock: 0,
    isPrescription: 0,
    categoryId: undefined,
    status: 1,
    sort: 0,
    mainImage: '',
    images: [],
    price: 0,
    originalPrice: 0,
    memberPrice: 0,
    manufacturer: '',
    approvalNumber: '',
    specification: '',
    usage: '',
    precautions: '',
    symptoms: []
  }

  if (formRef.value) {
    formRef.value.resetFields()
  }
  mainImageList.value = []
  imageList.value = []
}

const handleClose = () => {
  dialogVisible.value = false
}

const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val
  getList()
}

const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val
  getList()
}

const handleMainImageRemove = () => {
  mainImageList.value = []
  form.value.mainImage = ''
}

const handleImageRemove = (file: any) => {
  const index = imageList.value.findIndex(item => item.url === file.url)
  if (index !== -1) {
    imageList.value.splice(index, 1)
    form.value.images = imageList.value.map(item => item.url)
  }
}

onMounted(() => {
  loadCategories()
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-item {
  display: inline-block;
  vertical-align: middle;
  margin-bottom: 10px;
}

.table-container {
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.upload-box {
  margin-bottom: 10px;
}

.upload-tip {
  font-size: 12px;
  color: #999;
}
</style>